<?php

/**
 * 花费时间的计时器
 * Class Cost
 */
class Cost
{
    public static $list = [];
    public static $open = 0; //是否计时, 1: 打开 0: 关闭

    public static function open()
    {
        self::$open = 1;
    }

    public static function close()
    {
        self::$open = 0;
    }

    public static function start($key)
    {
        if (self::$open) {
            self::$list[$key]['start'] = microtime(true);
        }
    }

    public static function over($key)
    {
        if (self::$open) {
            self::$list[$key]['over'] = microtime(true);
        }
    }

    public static function info($key = '')
    {
        if (!empty($key) && !empty(self::$list[$key]['over'])) {
            self::$list[$key]['cost'] = bcsub(self::$list[$key]['over'], self::$list[$key]['start'], 4);
            return self::$list[$key];
        } else {
            foreach (self::$list as $key => $time) {
                self::$list[$key]['cost'] = bcsub(self::$list[$key]['over'], self::$list[$key]['start'], 4);
            }
            return self::$list;
        }
    }
}

// Cost::open();

// Cost::start('aaa');
// sleep(1);
// Cost::over('aaa');

// Cost::start('bbb');
// sleep(2);
// Cost::over('bbb');

// Cost::start('ccc');
// sleep(3);
// Cost::over('ccc');

// Cost::start('eee');
// sleep(4);
// Cost::over('eee');

// echo '<pre>';print_r(Cost::info());

// Array
// (
//     [aaa] => Array
//         (
//             [start] => 1627884317.9906
//             [over] => 1627884318.9906
//             [cost] => 1.0000
//         )

//     [bbb] => Array
//         (
//             [start] => 1627884318.9906
//             [over] => 1627884320.9906
//             [cost] => 2.0000
//         )

//     [ccc] => Array
//         (
//             [start] => 1627884320.9906
//             [over] => 1627884323.9906
//             [cost] => 3.0000
//         )

//     [eee] => Array
//         (
//             [start] => 1627884323.9906
//             [over] => 1627884327.9906
//             [cost] => 4.0000
//         )

// )